<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/app/admin/component/layui/css/layui.css" />
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/static/css/common.css" />
    <script src="/app/user/js/jquery.min.js"></script>
    <script src="/app/admin/component/layui/layui.js"></script>
    <script src="/app/admin/component/pear/pear.js"></script>
    <style>
        .layui-table{width: 100% !important;}
        .table-btn {height: 26px;line-height: 26px;}
        .table-btn+.table-btn {
            margin-left: 10px;
        }
        .form-style{padding-right: 50px;padding-bottom: 50px;padding-top: 20px;box-sizing: border-box;position: relative}
        .hide {display: none;}
        /*显示多行文本*/
        .layui-table-cell {
            height: auto;
            white-space: normal;
        }
    </style>
</head>
<body class="pear-container">
<div class="layui-card">

    <form class='layui-form' id="formData"></form>
<div class="layui-card-body">
    <table class="layui-hide" id="data-table">
        <script type="text/html" id="toolbarDemo">
                <!--                <button class="layui-btn pear-btn pear-btn-primary pear-btn-sm"   lay-event="restart"  >重启</button>-->
                <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="updateForm" permission="app.admin.rule.insert">
                    <i class="layui-icon layui-icon-add-1"></i>新增
                </button>
                <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove" permission="app.admin.rule.delete">
                    <i class="layui-icon layui-icon-delete"></i>删除
                </button>
        </script>
        <script type="text/html" id="is_enable">
            <input type="checkbox" value="{{d.id}}" lay-skin="switch" lay-text="是|否" lay-filter="task_status" {{ d.status== 1 ? 'checked' : '' }}>
        </script>
        <script type="text/html" id="btn1">
            <button type="button" class="layui-btn pear-btn pear-btn-xs pear-btn-primary table-btn" lay-event="runOne" >执行</button>
            <button type="button" class="layui-btn pear-btn pear-btn-sm pear-btn-primary table-btn" onclick="openEdit('{{d.id}}')">编辑
            </button>
            <button type="button" class="layui-btn table-btn pear-btn-sm layui-btn-info" onclick="renderLog('{{d.id}}','{{d.title}}')">日志</button>
            <button type="button" class="layui-btn pear-btn-sm layui-btn-danger" lay-event="delObj" >删除</button>
        </script>
        <script type="text/html" id="titleTpl">
            <div class="flex fl ftb">
                {{#  if(d.singleton == 0){ }}
                <button type="button" class="layui-btn layui-btn-sm pear-btn-primary">单次</button>
                {{#  } else { }}
                <button type="button" class="layui-btn layui-btn-sm">循环</button>
                {{#  } }}
                <div class="mal5 layui-font-12">
                    <div>{{d.title}} （周期：<span class="cblue">{{d.rule_name}}</span>） </div>
                    <div>指令：{{d.target}} </div>
                </div>
            </div>
        </script>


        <script type="text/html" id="statusTpl">
            <div class="flex fl ftb layui-font-12">
                {{#  if(d.logs.length == 0){ }}
                <div class="mal10">
                    未执行
                </div>
                {{# }else{ }}
                <div class="mal10">
                    <div>执行时间：{{d.last_running_time}} <span class="cgreen2">（耗时：{{d.logs[0].running_time}}）</span> 已执行<span class="cblue2">{{d.running_times}}</span>次</div>
                    <div>执行结果：<span class="cblue">{{d.logs[0].log}}</span></div>
                </div>
                {{# } }}
            </div>
        </script>

    </table>
</div>
</div>

<form class="layui-form layui-fluid form-style hide" id="updateForm">

    <input type="hidden" name="id" value="" id="id">

    <div class="layui-form-item" >
        <label class="layui-form-label">任务名称</label>
        <div class="layui-input-block">
            <input name="title" id="title" autocomplete="off" class="layui-input" type="text">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">任务类型</label>
        <div class="layui-input-inline">
            <select name="type" id="type" class="task_select">
                <option value="1">url</option>
                <option value="2">eval</option>
                <option value="3">shell</option>
            </select>
        </div>
        <div class="layui-input-inline">
        <select lay-filter="task_config" id="task_config" >
            <option value="" selected>--请选择内置任务--</option>
            <?foreach($taskConfig as $v){?>
                <option value="<?=$v['target']?>"><?=$v['title']?></option>
            <?}?>
        </select>
        </div>


    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">执行周期</label>
        <div class="layui-inline" style="width:90px">
            <select lay-filter="task_cycle" id="task_cycle" name="task_cycle">
                <option selected=""></option>
                <option value="1">每天</option>
                <option value="2">每小时</option>
                <option value="3">N小时</option>
                <option value="4">N分钟</option>
                <option value="5">N秒</option>
                <option value="6">每星期</option>
                <option value="7">每月</option>
                <option value="8">每年</option>
            </select>
        </div>
        <div style="display: inline-block" id="cron-box"></div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">调用目标</label>
        <div class="layui-input-block">
            <textarea placeholder="任务调用目标" name="target" id="target"  class="layui-textarea"></textarea>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">是否启用</label>
        <div class="layui-input-block">
            <input name="status" checked value="1" title="是" type="radio">
            <input name="status" value="0" title="否" type="radio">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">单次执行</label>
        <div class="layui-input-block">
            <input name="singleton" value="0" title="是" type="radio">
            <input name="singleton" checked value="1" title="否" type="radio">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" onclick="submitData()" type="button" >立即提交</button>
        </div>
    </div>
</form>

<script>

    const PRIMARY_KEY = "id";
    const SELECT_API = "/app/tuCrontabs/Crontabs/list";
    const GET_API = "/app/tuCrontabs/Crontabs/get";
    const EDIT_API = "/app/tuCrontabs/Crontabs/edit";
    const UPSTATUS_API = "/app/tuCrontabs/Crontabs/upstatus";
    const GETLOG_URL = "/app/tuCrontabs/Crontabs/getLog";
    const RESTART_API = "/app/tuCrontabs/Crontabs/reloadTask";
    const RUNONE_API = "/app/tuCrontabs/Crontabs/runOne";
    const DELETE_API = "/app/tuCrontabs/Crontabs/delete";

    layui.use(['table'],function(){
        let table = layui.table;
        let form = layui.form;
        let layer = layui.layer;

        let $ = layui.$;

        table.render({
            elem: '#data-table'
            , url: SELECT_API
            , toolbar: '#toolbarDemo'
            , method: "post",
            cellMinWidth: 80 //全局定义常规单元格的最小宽度
            , cols: [[
                {field: 'id', title: 'ID', width: 80}
                , {field: 'title', title: '任务名称',templet: '#titleTpl'}
                // , {field: 'target', title: '任务计划',templet: '#contentTpl'}
                , {field: 'target', title: '执行状态',templet: '#statusTpl',width:400}

                // , {field: 'rule_name', title: '执行周期', width: 180}
                // , {field: 'target', title: '调用目标',width: 300}
                // , {field: 'running_times', title: '运行次数', width: 90}
                // , {field: 'last_running_time', title: '上次运行时间', width: 165}
                , {field: '', title: '启用', templet: "#is_enable", width: 110}
                // , {field: 'create_time', title: '创建时间', sort: true, width: 165}
                , {field: '', title: '操作', templet: '#btn1', width: 320}
            ]]
            , page: true,
        });

        //监听任务执行周期切换
        form.on("select(task_cycle)", function (data) {
            let value = parseInt(data.value);
            changeTask(value)
        })

        // 监听内置任务
        form.on("select(task_config)",function(data){
            let text = data.elem.selectedOptions[0].text;
            let value = data.value;
            if(value){
                $('input[name="title"]').val(text);
                $('#type').val('2');
                $('textarea[name="target"]').val(value);
                form.render();
            }
        })

        form.on('switch(task_status)', function (obj) {
            let id = this.value;
            let state = obj.elem.checked ? 1 : 0;
            $.post(UPSTATUS_API,{id,state},function(res){
                if(res.code==1){
                    layer.msg(res.msg,{icon:5});
                }
            })
        });

        table.on('tool(data-table)',function(obj){
            let value = obj.data[PRIMARY_KEY];
            if(obj.event == 'runOne'){
                // 执行1次
                let value = obj.data[PRIMARY_KEY];
                $.get(RUNONE_API,{id:value},function(res){
                    if(res.code==1){
                        layer.msg(res.msg,{icon:5});
                    }else{
                        layer.msg(res.msg,{icon:1});
                        table.reload("data-table");
                    }
                })
            }else if(obj.event=='delObj'){
                layer.confirm("确定删除?", {
                    icon: 3,
                    title: "提示"
                }, function(index) {
                    layer.close(index);
                    let loading = layer.load();
                    $.get(DELETE_API,{id:value},function(res){
                        layer.close(loading);
                        if(res.code==0){
                            return obj ? obj.del() : table.reload("data-table");
                        }
                    })
                });
            }
        })

        // 顶部事件监听
        table.on("toolbar(data-table)", function(obj) {
            if (obj.event === "restart") {
                $.get(RESTART_API,function(res){
                    layer.msg(res.msg)
                })
            } else if (obj.event === "updateForm") {
                // 新增数据
                openWindow('updateForm')
            } else if (obj.event === "clearAll") {

            }
        });

    })



    //任务类型切换
    function changeTask(value){
        let month = `
	    <div class="layui-inline">
            <div class="layui-input-inline" style="width: 80px">
                <input type="text" name="month" id="month" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">月</div>
        </div>
		`
        let week = `
		<div class="layui-inline">
            <div class="layui-input-inline" style="width: 80px">
                <select lay-filter="week" name="week">
                    <option value="1" selected="">周一</option>
                    <option value="2">周二</option>
                    <option value="3">周三</option>
                    <option value="4">周四</option>
                    <option value="5">周五</option>
                    <option value="6">周六</option>
                    <option value="0">周日</option>
                </select>
            </div>
        </div>
		`;

        let day = `
	    <div class="layui-inline">
            <div class="layui-input-inline" style="width: 80px">
                <input type="text" name="day" id="day" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">号</div>
        </div>
		`
        let hour = `
        <div class="layui-inline">
            <div class="layui-input-inline" style="width: 80px">
                <input type="text" name="hour" id="hour" value="0" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">点</div>
        </div>
        `
        let minute = `
          <div class="layui-inline">
            <div class="layui-input-inline" style="width: 80px">
                <input type="text" name="minute" id="minute" value="30" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">分</div>
        </div>
        `
        let second = `
        <div class="layui-inline">
            <div class="layui-input-inline" style="width:80px">
                <input type="text" name="second" id="second" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">秒   尽量不要设置低于5秒的任务，容易出现异常</div>
        </div>
        `
        let insert_arr = [];
        switch (value) {
            case 1:
                insert_arr.push(hour,minute);
                break;
            case 2:
                insert_arr.push(minute);
                break;
            case 3:
                insert_arr.push(hour);
                insert_arr.push(minute);
                break;
            case 4:
                insert_arr.push(minute);
                break;
            case 5:
                insert_arr.push(second);
                break;
            case 6:
                insert_arr.push(week,hour,minute)
                break;
            case 7:
                insert_arr.push(day,hour,minute)
                break;
            case 8:
                insert_arr.push(month,day,hour,minute);
                break;
        }
        $('#cron-box').empty();
        for (let i in insert_arr){
            let item = insert_arr[i];
            $('#cron-box').append(item);
        }
        layui.form.render('select');
    }

    // 弹出框
    function openWindow(id,success=()=>{},end=()=>{}){
        layer.open({
            type: 1,
            skin: 'layui-layer-rim',
            content: $('#'+id),
            title: '信息',
            area: ['70%', '80%'], //宽高
            zIndex:9999999,
            success: function () {
                success();
                layui.form.render();

            },
            end: function () {
                end();
                $('#'+id).hide();
            }
        })
    }

    // 修改提交数据
    function submitData(){
        let formData = new FormData($('#updateForm')[0]);
        return $.ajax({
            url: EDIT_API,
            data: formData,
            type: 'post',
            dataType: 'json',
            async: true,
            processData: false,
            contentType: false,
            success: function (res) {
                if (res.code == 0){
                    layer.closeAll();
                    layui.layer.msg(res.msg)
                    //延迟刷新
                    setTimeout(()=>{
                        layui.table.reload("data-table");
                    },500)
                }else{
                    layui.layer.msg(res.msg)
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown,) {
                layui.layer.msg('请求失败')
            },
        })
    }



    //打开编辑窗口
    function openEdit(id) {
        return $.ajax({
            url: GET_API,
            data:  {'id': id},
            type: 'post',
            dataType: 'json',
            async: true,
            processData: true,
            contentType: false,
            success: function (res) {
                openWindow('updateForm',()=>{
                    let info = res.data;
                    $('#updateForm').find("input[name='status'][value='" + info.status + "']").prop("checked", true);
                    $('#updateForm').find("input[name='singleton'][value='" + info.singleton + "']").prop("checked", true);
                    changeTask(info.task_cycle)
                    let cycle_rule = info.cycle_rule;
                    for (let key in info) {
                        if (typeof (info[key]) == 'string' || typeof (info[key]) == 'number') {
                            $('#' + key).val(info[key]);
                        }
                    }
                    for (let key in cycle_rule) {
                        if (typeof (cycle_rule[key]) == 'string' || typeof (cycle_rule[key]) == 'number') {
                            $('#' + key).val(cycle_rule[key]);
                        }
                    }
                    layui.form.render();
                },()=>{
                    //关闭编辑弹窗清掉数据
                    let clear_arr = ['id','title','type','rule','target','status','singleton','task_cycle'];
                    for (let i in clear_arr){
                        let field = clear_arr[i];
                        $('#updateForm').find('#'+field).val('')
                    }
                    $('#cron-box').empty();
                })
            },
            error: function (XMLHttpRequest, textStatus, errorThrown,) {
                layui.layer.msg('请求失败')
            },
        })
    }

    //查看日志
    function renderLog(value,title) {
        layui.layer.open({
            type: 2,
            title: "日志查看 - "+title,
            shade: 0.1,
            area:  ['70%', '80%'],
            content: GETLOG_URL + "?" + PRIMARY_KEY + "=" + value
        });
    }


    $('body').on('click','#restart',function () {
    })
</script>

</body>
</html>
